package com.example.yskjproject.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.yskjproject.MainActivity;
import com.example.yskjproject.R;
import com.example.yskjproject.content.EventContent;
import com.example.yskjproject.event.EventMessage;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.model.OrderListModel;
import com.example.yskjproject.model.RechargeModel;
import com.example.yskjproject.model.WithDrawalRecordListModel;
import com.example.yskjproject.model.WithDrawalRecordModel;
import com.example.yskjproject.ui.fragment.WalletFragment;
import com.example.yskjproject.utils.DateUtils;
import com.example.yskjproject.utils.EventBusUtil;
import com.example.yskjproject.view.dialog.LoginWorkDialogHelper;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.qcloud.tuicore.util.ToastUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class OrderPageAdapter extends RecyclerView.Adapter<OrderPageAdapter.ViewHolder> {
    public List<OrderListModel.OrderListBean> mOrderListModel;
    private Context mContext;
    private Gson gson = new Gson();

    public void addData(List<OrderListModel.OrderListBean> orderListModel, Context context) {
        mOrderListModel = orderListModel;
        mContext = context;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_order, parent, false);
        return new ViewHolder(view);
    }

    @SuppressLint("SetTextI18n")
    @RequiresApi(api = Build.VERSION_CODES.S)
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        OrderListModel.OrderListBean orderListModel = mOrderListModel.get(position);

//        holder.tvTitle.setText("工作室名称："+orderListModel.getSeller_user().getNick_name());
        if (orderListModel.getOrder_type() == 1) {
            holder.tvTitle.setText(orderListModel.getStudio_info().getTitle());
            holder.tvCourseName.setText("课程名称:" + orderListModel.getCourse_info().getCourse_name());
        } else if (orderListModel.getOrder_type() == 2){
            holder.tvTitle.setText("代币充值");
            holder.tvCourseName.setText("原身代币充值");
        } else if (orderListModel.getOrder_type() == 3) {
            holder.tvTitle.setText("充值余额");
            holder.tvCourseName.setText("余额充值");
        }
        Glide.with(mContext).load(orderListModel.getOrder_img())//圆角半径
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(10)))//圆角半径
                .into(holder.ivImage);
        holder.tvOrderNumber.setText("订单编号："+orderListModel.getOrder_sn());
        if (orderListModel.getCourse_info() != null) {
            holder.tvDuration.setText("共" + orderListModel.getCourse_info().getDuration()%60 + "分钟");
        }
        if (orderListModel.getOrder_type() == 1 && orderListModel.getCoach_user_id() == orderListModel.getUser_id()) {
            holder.tvConsumeOrder.setText("收入订单");
        } else {
            holder.tvConsumeOrder.setText("消费订单");
        }

        if (orderListModel.getPay_type().equals("balance")) {
            holder.tvPayType.setText("余额支付");
            holder.secondIcon.setImageResource(R.drawable.balance);
            holder.tvPaymentAmount.setText(orderListModel.getBalance() + "");
        } else if (orderListModel.getPay_type().equals("wechat")) {
            holder.tvPayType.setText("微信支付");
            holder.secondIcon.setImageResource(R.drawable.wechat);
            holder.tvPaymentAmount.setText(orderListModel.getPaid_price() + "");
        } else if (orderListModel.getPay_type().equals("virtual_coin")) {
            holder.tvPayType.setText("代币支付");
            holder.secondIcon.setBackgroundResource(R.drawable.token);
            holder.tvPaymentAmount.setText(orderListModel.getVirtual_coin()/100 + "");
        }

        holder.tvOrderState.setText(orderListModel.getState() == 1 ? "已取消" : orderListModel.getState() == 2 ? "已支付" : orderListModel.getState() == 3 ? "退款中" : orderListModel.getState() == 4 ? "退款成功" : orderListModel.getState() == 0 ? "待支付":"未知");
        if (holder.tvOrderState.getText().equals("退款中")) {
            holder.btnRefund.setText("退款中");
            holder.btnRefund.setClickable(false);
        }
        holder.tvPayTime.setText(orderListModel.getPaid_at()+"");
        if (orderListModel.getPay_type().equals("virtual_coin")) {
            holder.btnRefund.setVisibility(View.GONE);
        } else {
            holder.btnRefund.setVisibility(View.VISIBLE);
        }
        if (DateUtils.compareTime(orderListModel.getPaid_at())) {
            holder.btnRefund.setClickable(false);
            ToastUtil.toastLongMessage("当前订单超过24小时，无法申请退款");
            holder.btnRefund.setVisibility(View.GONE);
        } else {
            holder.btnRefund.setClickable(true);
            holder.btnRefund.setVisibility(View.VISIBLE);
        }
        holder.btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkGo.<LzyResponse>get(Urls.DELETE_ORDER + "?order_id=" + orderListModel.getId()).execute(new JsonCallback<LzyResponse>() {
                    @Override
                    public void onSuccess(Response<LzyResponse> response) {
                        if (response.body() == null){
                            ToastUtil.toastShortMessage("服务器返回为空！");
                            return;
                        }
                        if (TextUtils.equals("ok", response.body().msg)) {
                            notifyItemChanged(position);
                        }else {
                            ToastUtil.toastShortMessage(response.body().msg);
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse> response) {
                        super.onError(response);
                    }
                });
            }
        });

        holder.btnRefund.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                View dialogView;
                AlertDialog dialogProgress;
                dialogView = ((Activity)mContext).getLayoutInflater().inflate(R.layout.request_refund, null);
                builder.setView(dialogView);
                dialogProgress = builder.create();
                dialogProgress.setCancelable(true);
                dialogProgress.show();
                dialogProgress.findViewById(R.id.bt_qx).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogProgress.dismiss();
                    }
                });
                dialogProgress.findViewById(R.id.bt_ok).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        refundOrder(orderListModel.getOrder_sn(),holder.btnRefund,position);
                        dialogProgress.dismiss();
                    }
                });
            }
        });
        holder.btnBuyAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginWorkDialogHelper loginWorkDialogHelper = new LoginWorkDialogHelper(mContext, orderListModel.getStudio_id());
                loginWorkDialogHelper.show();
            }
        });

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (orderListModel.getOrder_type() == 1) {
                    LoginWorkDialogHelper loginWorkDialogHelper = new LoginWorkDialogHelper(mContext, orderListModel.getStudio_id());
                    loginWorkDialogHelper.show();
                } else {
                    MainActivity mainActivity = (MainActivity) mContext;
                    mainActivity.show(9,-1);
                }
            }
        });

    }

    public void refundOrder(String orderSN,AppCompatButton btnRefund,int position) {
        Map<String, Object> jsonParams = new HashMap<>();
        jsonParams.put("order_sn", orderSN);
        String paramsDate = gson.toJson(jsonParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
        OkGo.<LzyResponse<String>>post(Urls.REFUND_APPLY).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<String>>() {

            @Override
            public void onSuccess(Response<LzyResponse<String>> response) {
                btnRefund.setText("退款中");
                notifyItemChanged(position);
            }

            @Override
            public void onError(Response<LzyResponse<String>> response) {
                super.onError(response);
                ToastUtil.toastLongMessage("申请退款失败");
            }
        });

    }

    @Override
    public int getItemCount() {
        return mOrderListModel.size();
    }


    public static class ViewHolder extends RecyclerView.ViewHolder {
        private AppCompatTextView tvTitle;
        private AppCompatTextView tvOrderState;
        private AppCompatImageView ivImage;
        private AppCompatTextView tvOrderNumber;
        private AppCompatTextView tvCourseName;
        private AppCompatImageView firstIcon;
        private AppCompatImageView secondIcon;
        private AppCompatTextView tvConsumeOrder;
        private AppCompatTextView tvPayType;
        private AppCompatTextView tvPayTime;
        private AppCompatTextView tvPaymentAmount;
        private AppCompatTextView tvDuration;
        private AppCompatButton btnDelete;
        private AppCompatButton btnRefund;
        private AppCompatButton btnBuyAgain;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tv_title);
            tvOrderState = itemView.findViewById(R.id.tv_order_status);
            ivImage = itemView.findViewById(R.id.iv_image);
            tvOrderNumber = itemView.findViewById(R.id.tv_order_number);
            tvCourseName = itemView.findViewById(R.id.tv_course_name);
            firstIcon = itemView.findViewById(R.id.first_icon);
            secondIcon = itemView.findViewById(R.id.second_icon);
            tvConsumeOrder = itemView.findViewById(R.id.tv_consume_order);
            tvPayType = itemView.findViewById(R.id.pay_type);
            tvPayTime = itemView.findViewById(R.id.tv_payment_time);
            tvPaymentAmount = itemView.findViewById(R.id.tv_payment_amount);
            tvDuration = itemView.findViewById(R.id.tv_duration);
            btnDelete = itemView.findViewById(R.id.btn_delete);
            btnRefund = itemView.findViewById(R.id.btn_refund);
            btnBuyAgain = itemView.findViewById(R.id.btn_buy_again);

        }
    }
}
